package com.gy.edu.home;

import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.widget.ListView;

import com.artifex.mupdf.MuPDFCore;
import com.artifex.mupdf.MuPDFPageAdapter;
import com.gy.edu.R;
import com.gy.edu.base.BaseActivity;
import com.gy.edu.teach.adapter.TeachPagerAdAdapter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by 高岳 on 2016/12/24.
 * Describe:
 */
public class FileDetailActivity extends BaseActivity {

    private ListView mListView;
    private ViewPager viewPager;
    private String path = "/sdcard/test/";
    private String fileName = "aa.pdf";
    private TeachPagerAdAdapter pagerAdAdapter;

    @Override
    protected void initView() {
        setContentViewRes(R.layout.activity_file_detail);
        _rlTitle.setBackgroundColor(Color.parseColor("#000000"));
        setTitleMsg("教案_汽车电器设备基础");
        _baseTitle.setTextColor(Color.parseColor("#ffffff"));
        mListView = (ListView) findViewById(R.id.listview_main);
        viewPager = (ViewPager) findViewById(R.id.teach_viewpager);
        File file = new File(path + fileName);
        if (!file.exists()) {
            try {
                InputStream inputStream = getResources().getAssets().open(fileName);
                write(fileName, inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        String paths = path + fileName;
        MuPDFCore core = null;
        try {
            core = new MuPDFCore(this, paths);
        } catch (Exception e) {

        }
        MuPDFPageAdapter adapter = new MuPDFPageAdapter(this, core);
        mListView.setAdapter(adapter);
        pagerAdAdapter = new TeachPagerAdAdapter(this, core);
        viewPager.setAdapter(pagerAdAdapter);
    }

    @Override
    protected void initData() {

    }

    private void write(String filename, InputStream in) {

        File file = new File(path);
        if (!file.exists()) {
            if (!file.mkdirs()) {//若创建文件夹不成功
                System.out.println("Unable to create external cache directory");
            }
        }

        File targetfile = new File(path + filename);
        OutputStream os = null;
        try {
            os = new FileOutputStream(targetfile);
            int ch = 0;
            byte[] buffer = new byte[8192];
            while ((ch = in.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, ch);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
